package bacnetnetwork1;

import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.service.acknowledgement.*;
import com.serotonin.bacnet4j.service.confirmed.*;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.constructed.Address;
import com.serotonin.bacnet4j.type.enumerated.PropertyIdentifier;
import com.serotonin.bacnet4j.type.enumerated.Segmentation;
import com.serotonin.bacnet4j.type.primitive.*;
import com.serotonin.bacnet4j.type.primitive.Boolean;



public class Communicate {    
    
    public Communicate(){}
    
    public Encodable communicateRead (LocalDevice who, String address, int port, ObjectIdentifier objId, PropertyIdentifier prId) throws Exception{
        
        AcknowledgementService result=who.send(new Address(convertToBytes(address),port), null, 35, Segmentation.segmentedBoth, new ReadPropertyRequest(objId,prId));
        
        return ((ReadPropertyAck)result).getValue();
    }
    
    public void communicateWriteReal (LocalDevice who, String address, int port, ObjectIdentifier objId, PropertyIdentifier prId, float value) throws Exception{
        
        who.send(new Address(convertToBytes(address),port), null, 35, Segmentation.segmentedBoth, new WritePropertyRequest(objId, prId, null, new Real(value), new UnsignedInteger(5)));

    }
    
    public void communicateWriteBoolean (LocalDevice who, String address, int port, ObjectIdentifier objId, PropertyIdentifier prId, boolean value) throws Exception{
        
        who.send(new Address(convertToBytes(address),port), null, 35, Segmentation.segmentedBoth, new WritePropertyRequest(objId, prId, null, new Boolean(value), new UnsignedInteger(5)));

    }
    
    
    public byte[] convertToBytes(String address){
        int idx1=address.indexOf(".",0);
        int idx2=address.indexOf(".",idx1+1);
        int idx3=address.indexOf(".",idx2+1);
        
              
        String value1=address.substring(0, idx1);
        String value2=address.substring(idx1+1, idx2);
        String value3=address.substring(idx2+1, idx3);
        String value4=address.substring(idx3+1, address.length());     
        
        byte[] addressBytes= new byte[] {(byte)Integer.parseInt(value1), (byte)Integer.parseInt(value2), (byte)Integer.parseInt(value3), (byte)Integer.parseInt(value4)};
        
        return addressBytes;
    }
    
}
